<?php
/**
    flickr_sync v0.1.2
    Copyright 2010 Markus Dolic (crowley@gmx.net)
    
    This file is part of the flickrpost package. 
    (http://code.google.com/p/flickrpost/)
    
    flickrpost is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
    flickrpost is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
    You should have received a copy of the GNU General Public License
    along with flickrpost.  If not, see <http://www.gnu.org/licenses/>. 
**/

//error_reporting(E_ALL);
require_once(dirname(__FILE__)."/inc/common.php");


$GLOBALS['FLICKR_SYNC_TABLE_CFG'] = $TABLE_SYNC_CFG;
$GLOBALS['FLICKR_SYNC_TABLE_DATA'] = $TABLE_SYNC_DATA;

$addon_name = "flickr_sync<a name='flickr_sync'></a>";
$addon_version = "0.1.2";
$addon_description = "";

$errormsg = '';

// create DBs if they do not exist yet
if (!mysql_query("SELECT * FROM $TABLE_SYNC_CFG LIMIT 1")) {
    mysql_query("CREATE TABLE IF NOT EXISTS $TABLE_SYNC_CFG (
                     `def_tags` CHAR(255), 
                     `orig_linktext` CHAR(255)
                )") or die(mysql_error());
	mysql_query("INSERT INTO $TABLE_SYNC_CFG VALUES('pixelpost flickrpost', '[source]')") or die(mysql_error()); // insert default config record
}
if (!mysql_query("SELECT * FROM $TABLE_SYNC_DATA LIMIT 1")) {
    mysql_query("CREATE TABLE IF NOT EXISTS $TABLE_SYNC_DATA (
                     `fk_pp_id` INT(11), 
                     `flickr_id` CHAR(20)
                )") or die(mysql_error());
}

// populate config variables from config DBs
$result = mysql_query("SELECT * FROM $TABLE_AUTH LIMIT 1") or $errormsg .= 'Could not retrieve flickr authentication data: ' . mysql_error() . '<br />';
while ($cfg = mysql_fetch_array($result)) {
    $api_key = $cfg['api_key'];
    $api_secret = $cfg['api_secret'];
    $api_perm = $cfg['api_perm'];
    $api_token = $cfg['api_token'];
}
if ($api_perm != 'delete') {
    $errormsg .= "flickr_sync requires flickr API access with <strong>delete</strong> permissions. <br />";
}

$result = mysql_query("SELECT * FROM $TABLE_SYNC_CFG LIMIT 1");
while ($cfg = mysql_fetch_array($result)) {
    $def_tags = $cfg['def_tags'];
    $orig_linktext = $cfg['orig_linktext'];
}
$GLOBALS['FLICKR_SYNC_DEF_TAGS'] = $def_tags;
$GLOBALS['FLICKR_SYNC_ORIG_LINKTEXT'] = $orig_linktext;

// initialize flickr API proxy object
$_SESSION['phpFlickr_auth_token'] = $api_token;
$flickr = new phpFlickr($api_key, $api_secret, true);
$GLOBALS['FLICKR_SYNC_FLICKR'] = $flickr;

// process POST requests
if (isset($_POST['flickr_sync_do'])) {
    if ($_POST['flickr_sync_do'] == 'config') {
        $def_tags = trim($_POST['def_tags']);
        $orig_linktext = $_POST['orig_linktext'];
        mysql_query("UPDATE " . $TABLE_SYNC_CFG . " SET def_tags='$def_tags', orig_linktext='$orig_linktext'") or die(mysql_error());
        $_SESSION['flickr_sync_result'] = 'Configuration saved. ';
    }
}


if (isset($errormsg) and $errormsg != '') {
    $addon_description .= "<div class='confirm'>Error: <br />{$errormsg}</div><br />";
}

if (isset($_SESSION['flickr_sync_result'])) {
    $addon_description .= "<em>" . $_SESSION['flickr_sync_result'] . '</em><hr />';
    unset($_SESSION['flickr_sync_result']);
}
$addon_description .= <<<EOT
    Configuration: 
    <form action='{$SITE_URL}admin/index.php?view=addons#flickr_sync' method='post' accept-charset='UTF-8'>
        <input type='hidden' name='flickr_sync_do' value='config' />
        <table>
            <tr>
                <td>Default additional tags (space-separated): </td>
                <td><input type='text' size='40' name='def_tags' value='{$def_tags}' /></td>
            </tr>
            <tr>
                <td>Text for link to blog post (leave empty to disable): </td>
                <td><input type='text' size='40' name='orig_linktext' value='{$orig_linktext}' /></td>
            </tr>
        </table>
        <input type='submit' value='Save' />
    </form>
EOT;


add_admin_functions('workspace_image_edit', 'image_edit', 'images', 'flickr_sync');
function workspace_image_edit()
{
    require_once('../includes/markdown.php');
    global $pixelpost_db_prefix, $cfgrow, $image, $headline, $body;
    $id = $_GET['id'];
    $flickr = $GLOBALS['FLICKR_SYNC_FLICKR'];
    $imgurl = $cfgrow['imagepath'] . $image;
    $thumburl = $cfgrow['thumbnailpath'] . 'thumb_' . $image;
    $cred = $flickr->auth_checkToken();
    $user = $cred['user'];
    $baseurl = "http://www.flickr.com/photos/{$user['nsid']}";
    $desc = markdown($body);
    
    // append link to original blog post to description: 
    $origlinktext = $GLOBALS['FLICKR_SYNC_ORIG_LINKTEXT'];
    if ($origlinktext != '') {
        $desc .= "<a href='{$cfgrow['siteurl']}index.php?showimage=$id'>$origlinktext</a>";
    }
    
    // retrieve tags for image
    $tagstr = '';
	$query = "SELECT DISTINCT tag FROM {$pixelpost_db_prefix}tags WHERE img_id = $id AND tag NOT LIKE '' ORDER BY tag ASC";
    $result = mysql_query($query);
	while (list($tag) = mysql_fetch_row($result)) $tagstr .= ' ' . (strpos($tag, ' ') ? "\"{$tag}\"" : $tag);
	$tagstr = $GLOBALS['FLICKR_SYNC_DEF_TAGS'] . ' ' . trim($tagstr);
    
    // check if image has already been uploaded
    $existing_ids_result = mysql_query("SELECT flickr_id FROM {$GLOBALS['FLICKR_SYNC_TABLE_DATA']} WHERE fk_pp_id=$id");
    
    echo "<div class='content'>";
    if (isset($_POST['do']) and $_POST['do'] == "upload") {
        set_time_limit(0);
        if (get_magic_quotes_gpc()) {
            $_POST['title'] = stripslashes($_POST['title']);
            $_POST['desc'] = stripslashes($_POST['desc']);
            $_POST['tags'] = stripslashes($_POST['tags']);
        }
        $imgid = $flickr->sync_upload($imgurl, $_POST['title'], $_POST['desc'], $_POST['tags']);
        mysql_query("INSERT INTO {$GLOBALS['FLICKR_SYNC_TABLE_DATA']} (fk_pp_id, flickr_id) VALUES ($id, $imgid)");
        echo "Successfully uploaded <strong>$image</strong> [ID#$id] to flickr: ID <a href='$baseurl/$imgid/'>$imgid</a>. ";
    }
    elseif (isset($_POST['do']) and $_POST['do'] == "delete") {
        $flickr->photos_delete($_POST['flickr_id']);
        mysql_query("DELETE FROM {$GLOBALS['FLICKR_SYNC_TABLE_DATA']} WHERE flickr_id={$_POST['flickr_id']}");
        echo "Deleted: <a href='$baseurl/{$_POST['flickr_id']}/'>{$_POST['flickr_id']}</a>";
    }
    elseif (mysql_num_rows($existing_ids_result)) {
        echo "Image has already been uploaded to flickr: ";
        while ($row = mysql_fetch_array($existing_ids_result)) {
            echo <<<EOT
                <form action='{$_SERVER["REQUEST_URI"]}' method='post'>
                    ID <a href='$baseurl/{$row['flickr_id']}/'>{$row['flickr_id']}</a>
                    <input type='hidden' name='do' value='delete' />
                    <input type='hidden' name='flickr_id' value='{$row['flickr_id']}' />
                    <input type='submit' value='Delete' />
                </form><br />
EOT;
        }
    }
    else {
        echo <<<EOT
            Modify the parameters as desired, then hit the button to upload <strong><a href='$imgurl'>$image</a></strong> [ID#$id] to flickr: 
            <hr />
            <form action='{$_SERVER["REQUEST_URI"]}' method='post'>
                <input type='hidden' name='do' value='upload' />
                <table>
                    <tr style='vertical-align:top;'>
                        <td>Title: </td>
                        <td><input type='text' style='width:98%;' name='title' value='{$headline}' /></td>
                        <td rowspan='3' style='text-align:right;'>
                            <img src='$thumburl' />
                            <br /><br />
                            <input type='submit' value='Upload' />
                        </td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Tags: </td>
                        <td><input type='text' style='width:98%;' name='tags' value='{$tagstr}' /></td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Description: </td>
                        <td><textarea type='text' rows='5' cols='50' name='desc'>{$desc}</textarea></td>
                    </tr>
                </table>
            </form>
EOT;
    }
    $uploadstat = $flickr->people_getUploadStatus();
    if (!$uploadstat['bandwidth']['unlimited']) {
        echo "<hr />Remaining upload bandwidth for <a href='$baseurl/'>{$user['username']}</a>: {$uploadstat['bandwidth']['remainingkb']} kb<br />";
    }
    echo "</div>";
}


add_admin_functions('workspace_image_deleted', 'image_deleted', '', '');
function workspace_image_deleted()
{
    // TODO...
}
?>
